package com.qiaofang.collectmanage.analysis;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Created with IDEA
 * 1.先获取元素
 * 此类方法值只允许，新增，不允许修改 ，修改需要review
 *
 * @author:ZJ.J
 * @Date:2018/6/6
 * @Time:14:24
 */
public class ReturnElement {

    private ReturnElement(){}
    /**
     * @param lastElement 最新html element
     * @param rule
     * @return 返回html elements
     */
    public static Elements select(Element lastElement, String rule) {
        return lastElement.select(rule);
    }

    /**
     * select 选择器
     *
     * @param lastElement 最新html element
     * @param args        args[0] 方法名称
     *                    args[1] select 参数
     *                    args[2] 根据index返回lement
     * @return 返回html element
     */
    public static Element select(Element lastElement, String... args) {
        Element element = null;
        Elements elements = lastElement.select(args[1]);
        int index = 0;
        if (args.length == 3) {
            index = Integer.valueOf(args[2]);
        }
        if (elements.size() > index) {
            element = elements.get(index);
        } else if (elements.size() > 0) {
            element = elements.get(0);
        }
        return element;
    }

    /**
     * selectList 选择器
     *
     * @param lastElement 最新html element
     * @param args        args[0] 方法名称
     *                    args[1] select 参数
     * @return 返回
     * <body>
     * <a>..</a>
     * <a>...</a>
     * </body>
     */
    public static Element selectList(Element lastElement, String... args) {
        Elements elements = lastElement.select(args[1]);
        return Jsoup.parse(elements.outerHtml()).body();
    }

    /**
     * 替换
     *
     * @param lastElement
     * @param args        args[1] oldstr
     *                    args[2]  newstr 默认为串
     * @return
     */
    public static Element replace(Element lastElement, String... args) {
        String oldStr;
        String newStr = "";
        if (args.length == 3) {
            oldStr = args[1];
            newStr = args[2];
        } else {
            oldStr = args[1];
        }
        return Jsoup.parse(lastElement.outerHtml().replace(oldStr, newStr)).body().children().first();
    }
}
